﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using Agile.Paypal.Web.Services;

namespace Agile.Paypal.Web
{
    public class PaypalIpnHttpHandler :  IHttpHandler 
    {
        private readonly IPaypalNotificationProcessor _processor;

        public PaypalIpnHttpHandler(IPaypalNotificationProcessor processor)
        {
            _processor = processor;
        }

        public void ProcessRequest(HttpContext context)
        {

            try
            {
                PaypalNotification paypalNotification = PaypalNotification.FromRequest(context.Request);

                if (!IsValid(context.Request, true))
                {
                    context.Response.StatusCode = 401;
                    return;
                }

                _processor.Process(paypalNotification);
                context.Response.StatusCode = 200;
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = 500;
            }
            
    

        }

        private static bool IsValid(HttpRequest request, bool debug)
        {
            string url = debug ? "https://www.sandbox.paypal.com/cgi-bin/webscr" : "https://www.paypal.com/cgi-bin/webscr";


            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            //Set values for the request back
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] param = request.BinaryRead(request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            strRequest += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;

            //for proxy
            //WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
            //req.Proxy = proxy;

            //Send the request to PayPal and get the response
            using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
                streamOut.Write(strRequest);

            using(WebResponse webResponse = req.GetResponse())
            using (StreamReader streamIn = new StreamReader(webResponse.GetResponseStream()))
                return streamIn.ReadToEnd() == "VERIFIED";




            // logging ipn messages... be sure that you give write
            // permission to process executing this code
            /*string logPathDir = ResolveUrl("Messages");
            string logPath = string.Format("{0}\\{1}.txt",
                             Server.MapPath(logPathDir), DateTime.Now.Ticks);
            File.WriteAllText(logPath, ipnPost);*/
            //



        }

        public bool IsReusable { get { return false; } }
    }
}
